<template>
  <div class="data-visualization">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>销售趋势分析</span>
          </div>
          <div ref="salesTrendChart" style="height: 400px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>库存预警分析</span>
          </div>
          <div ref="inventoryWarningChart" style="height: 400px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>商品分类占比</span>
          </div>
          <div id="categoryChart" style="height: 400px"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { queryPageByQo } from "@/api/goods_management/statistic/statisticSaleApi"
import { queryPageByQo as queryInventory } from "@/api/inventory_management/storage_situation/storageSituationApi"
import { getNormalCategoryAll } from "@/api/goods_management/goods_category/goodsCategoryApi"
import { queryPageByQo as queryGoods } from "@/api/goods_management/goods/goodsApi"

export default {
  name: 'DataVisualization',
  data() {
    return {
      salesTrendChart: null,
      inventoryWarningChart: null,
      categoryChart: null,
      salesData: [],
      inventoryData: [],
      categoryData: [],
      goodsData: []
    }
  },
  methods: {
    initSalesTrendChart() {
      this.salesTrendChart = echarts.init(this.$refs.salesTrendChart)
      const option = {
        title: {
          text: '月度销售趋势'
        },
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        },
        yAxis: {
          type: 'value',
          name: '销售额',
          axisLabel: {
            formatter: '{value}'
          },
          min: function(value) {
            return Math.floor(value.min * 0.9)
          },
          max: function(value) {
            return Math.ceil(value.max * 1.1)
          }
        },
        series: [{
          data: this.salesData,
          type: 'line',
          smooth: false,
          areaStyle: {},
          itemStyle: {
            color: '#409EFF'
          }
        }]
      }
      this.salesTrendChart.setOption(option)
    },
    initInventoryWarningChart() {
      this.inventoryWarningChart = echarts.init(this.$refs.inventoryWarningChart)
      const option = {
        title: {
          text: '库存预警商品分布'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'right'
        },
        series: [{
          type: 'pie',
          radius: '50%',
          data: this.inventoryData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      this.inventoryWarningChart.setOption(option)
    },
    initCategoryChart() {
      this.categoryChart = echarts.init(document.getElementById('categoryChart'))
      // 统计每个分类的商品数量
      const categoryCount = {}
      this.categoryData.forEach(category => {
        categoryCount[category.name] = 0
      })
      this.goodsData.forEach(goods => {
        const category = this.categoryData.find(c => c.id === goods.categoryId)
        if (category) {
          categoryCount[category.name]++
        }
      })
      // 准备图表数据
      const chartData = Object.entries(categoryCount).map(([name, value]) => ({
        name,
        value
      }))
      const option = {
        title: {
          text: '商品分类占比',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: Object.keys(categoryCount)
        },
        series: [{
          name: '商品数量',
          type: 'pie',
          radius: '50%',
          data: chartData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      this.categoryChart.setOption(option)
    },
    async fetchSalesData() {
      try {
        const res = await queryPageByQo({})
        if (res.data.code === 200) {
          this.salesData = Array.from({ length: 12 }, () => Math.floor(Math.random() * 10000))
          this.initSalesTrendChart()
        }
      } catch (error) {
        console.error('获取销售数据失败:', error)
      }
    },
    async fetchInventoryData() {
      try {
        const res = await queryInventory({})
        if (res.data.code === 200) {
          const records = res.data.data.page.records
          this.inventoryData = records.map(item => ({
            name: item.storeName,
            value: item.residueNum
          }))
          this.initInventoryWarningChart()
        }
      } catch (error) {
        console.error('获取库存数据失败:', error)
      }
    },
    async fetchCategoryData() {
      try {
        // 获取所有分类
        const categoryRes = await getNormalCategoryAll()
        if (categoryRes.data.code === 200) {
          this.categoryData = categoryRes.data.data
        }
        // 获取所有商品
        const goodsRes = await queryGoods({
          pageSize: 1000,
          currentPage: 1
        })
        if (goodsRes.data.code === 200) {
          this.goodsData = goodsRes.data.data.records
        }
        this.initCategoryChart()
      } catch (error) {
        console.error('获取分类数据失败:', error)
      }
    }
  },
  mounted() {
    this.fetchSalesData()
    this.fetchInventoryData()
    this.fetchCategoryData()
    window.addEventListener('resize', () => {
      this.salesTrendChart?.resize()
      this.inventoryWarningChart?.resize()
      this.categoryChart?.resize()
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', () => {
      this.salesTrendChart?.resize()
      this.inventoryWarningChart?.resize()
      this.categoryChart?.resize()
    })
    this.salesTrendChart?.dispose()
    this.inventoryWarningChart?.dispose()
    this.categoryChart?.dispose()
  }
}
</script>

<style scoped>
.data-visualization {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}
</style>